package edu.towson.cosc.cosc455.jkingsbury.compiler;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.lang.Character;
//import java.util.Scanner;

public class MyCompiler {
	public static String token;
	public static String peek;
	public static String content;
	static String result = "";
	//Create access to it
	static MyLexicalAnalyzer Lexer;
	static MySyntaxAnalyzer parser;
	static MySemanticAnalyzer generator;
	
	public static void main(String[] args) throws IOException {
		//Make sure token is empty
		token = "";
		//Checking if a file was inputed
		if(args.length != 1){
			System.err.println("No file argument was entered when one was expected.");
			System.exit(0);
		}
		
		//Reading in the file
		FileReader fr = new FileReader(args[0]);
		BufferedReader br = new BufferedReader(fr);
		String filename = args[0];
		String name = filename.substring(0, filename.lastIndexOf('.'));//Get filename for output file
		name += ".html";
		checkExt(filename);
		
		//Putting what is in the file into a string
		content = readFile(filename, Charset.defaultCharset());
		//Initialize parse tree array? Uhm...
		//Other initializations? Erm...
		
		//Chop up file into tokens
		//Gets token and puts it in bin
		Lexer = new MyLexicalAnalyzer();
		Lexer.start(content);
		Lexer.getNextToken();
		
		//Ready to start parsing
		parser = new MySyntaxAnalyzer();
		parser.lolcode();//Start state
		
		
		//Will create parse tree if everything is okay
		//Need to give meaning to parsing
		generator = new MySemanticAnalyzer();
		generator.begin();
		
		PrintWriter writer = new PrintWriter(name, "UTF-8");
		writer.println(result);
		writer.close();
		fr.close();
		br.close();
	}//End of main
	
	//Check extension
	public static void checkExt(String name){
		String extension = name.substring(name.lastIndexOf(".") +1, name.length());
		String ext = "lol";
		if (!ext.equalsIgnoreCase(extension)){//Do I want to ignore the case
			System.err.println("Was expecting .lol extenstion but instead got: ." + extension);
			System.exit(0);
		}
	}	
	//Write file to a string
	public static String readFile(String path, Charset encoding) throws IOException {
		byte[] encoded = Files.readAllBytes(Paths.get(path));
		return new String(encoded, encoding);
	}
}//End of class
